package com.wgz.medicalmanagement.common.exception;

import com.wgz.medicalmanagement.common.entity.Result;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.ResourceAccessException;

/**
 * 全局异常处理器
 * 处理应用中的各种异常
 *
 * @author medical
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理参数验证异常
     *
     * @param e 验证异常
     * @return 错误响应
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<Result<String>> handleValidationException(ConstraintViolationException e) {
        log.error("参数验证失败: {}", e.getMessage());
        return ResponseEntity.badRequest().body(Result.fail("参数验证失败: " + e.getMessage()));
    }
    
    /**
     * 处理外部API调用异常
     *
     * @param e HTTP客户端错误异常
     * @return 错误响应
     */
    @ExceptionHandler(HttpClientErrorException.class)
    public ResponseEntity<Result<String>> handleHttpClientErrorException(HttpClientErrorException e) {
        log.error("外部API调用失败: {}, 响应: {}", e.getMessage(), e.getResponseBodyAsString());
        return ResponseEntity
                .status(HttpStatus.SERVICE_UNAVAILABLE)
                .body(Result.fail("外部服务调用失败: " + e.getStatusCode()));
    }
    
    /**
     * 处理网络资源访问异常
     *
     * @param e 资源访问异常
     * @return 错误响应
     */
    @ExceptionHandler(ResourceAccessException.class)
    public ResponseEntity<Result<String>> handleResourceAccessException(ResourceAccessException e) {
        log.error("网络资源访问失败: {}", e.getMessage());
        return ResponseEntity
                .status(HttpStatus.SERVICE_UNAVAILABLE)
                .body(Result.fail("网络连接失败，请检查网络设置或稍后再试"));
    }
    
    /**
     * 处理一般异常
     *
     * @param e 一般异常
     * @return 错误响应
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Result<String>> handleGenericException(Exception e) {
        log.error("系统内部错误: ", e);
        return ResponseEntity
                .status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Result.fail("系统内部错误，请联系管理员"));
    }
} 